package com.springcloud.demo.controller;

import com.springcloud.demo.api.DemoRestService;
import com.springcloud.demo.api.DemoRpcService;
import com.springcloud.demo.model.Demo;
import com.xframework.security.api.SecurityRpcService;
import com.xframework.security.model.Account;
import com.xframework.security.model.SecurityAccount;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

/**
 * Created by xuning on 2020/8/26.
 */
@RestController
public class DemoConsumerController {

    @Autowired
    private DemoRestService demoRestService;

    @DubboReference
    private DemoRpcService demoRpcService;

    @DubboReference
    private SecurityRpcService securityRpcService;

    @RequestMapping(value = "/helloDemoConsumer")
    public Demo helloDemoConsumer(@RequestBody Demo demo) {
        System.out.println("demoId=" + demo.getDemoId());
        System.out.println("demoName=" + demo.getDemoName());
        demo = demoRestService.helloDemoProvider(demo);
        System.out.println("DemoProviderRestDemoId=" + demo.getDemoId());
        System.out.println("DemoProviderRestDemoName=" + demo.getDemoName());
        if (demo.getDemoName().equals("3")) {
            throw new RuntimeException("xxxxx");
        }
        return demo;
    }

    @RequestMapping(value = "/testException")
    public Demo testException(@RequestBody Demo demo) {
        System.out.println("demoId=" + demo.getDemoId());
        System.out.println("demoId=" + demo.getDemoName());
        try {
            demo = demoRpcService.helloDemoProvider(demo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("DemoProviderRpcDemoId=" + demo.getDemoId());
        System.out.println("DemoProviderRpcDemoName=" + demo.getDemoName());
        if (demo.getDemoId().equals("1")) {
            throw new RuntimeException("我错了");
        }
        return demo;
    }

    @RequestMapping(value = "/security")
    public SecurityAccount security(@RequestBody Demo demo) {
        System.out.println("demoId=" + demo.getDemoId());
        System.out.println("demoName=" + demo.getDemoName());
        Account account = new Account();
        account.setAccountName(demo.getDemoId());
        account.setAccountPassword(demo.getDemoName());
        SecurityAccount securityAccount = securityRpcService.selectAccount(account, "00000000000000000000000000000001", "x");
        return securityAccount;
    }

    @RequestMapping(value = "/helloDemoProviderGet")
    public Demo helloDemoProviderGet(@RequestBody Demo demo) {
        System.out.println("demoId=" + demo.getDemoId());
        System.out.println("demoName=" + demo.getDemoName());
        demo = demoRestService.helloDemoProviderGet(demo);
        return demo;
    }

}
